from django.http import JsonResponse
from datetime import datetime, timedelta
from django.db.models import Sum, Count
from BloodSpiderAPI import models
from BloodSpiderAPI.apis.order_v2 import utils as order_v2_utils


def get_order_analytics(request):
    """获取订单数据分析报告
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含订单数据分析报告的JSON响应
    """
    if request.method != 'GET':
        return order_v2_utils.response_dict(message="请使用GET请求", code=1)
    
    try:
        # 获取今天的日期
        today = datetime.now().date()
        today_start = datetime.combine(today, datetime.min.time())
        
        # 总发单量
        total_orders = models.OrderListV2.objects.count()
        
        # 今日发单量
        today_orders = models.OrderListV2.objects.filter(create_time__gte=today_start).count()
        
        # 各status状态的订单数量
        status_counts = models.OrderListV2.objects.values('status').annotate(count=Count('status')).order_by('status')
        status_data = {}
        status_text_map = dict(models.OrderListV2.STATUS_CHOICES)
        
        for item in status_counts:
            status_code = item['status']
            status_data[status_code] = {
                'code': status_code,
                'name': status_text_map[status_code],
                'count': item['count']
            }
        
        # 确保所有状态都有数据
        for code, name in models.OrderListV2.STATUS_CHOICES:
            if code not in status_data:
                status_data[code] = {
                    'code': code,
                    'name': name,
                    'count': 0
                }
        
        # 全部订单完成收益总和
        total_completed_profit = models.OrderListV2.objects.aggregate(total_profit=Sum('completed_profit'))['total_profit'] or 0
        
        # 今日订单完成收益总和
        today_completed_profit = models.OrderListV2.objects.filter(create_time__gte=today_start).aggregate(total_profit=Sum('completed_profit'))['total_profit'] or 0
        
        # 订单完成率
        completed_orders = models.OrderListV2.objects.filter(status=9).count()  # 已结算状态
        completion_rate = (completed_orders / total_orders * 100) if total_orders > 0 else 0
        
        # 已完结订单收益总和（状态为9的订单）
        settled_orders_profit = models.OrderListV2.objects.filter(status=9).aggregate(total_profit=Sum('completed_profit'))['total_profit'] or 0
        
        # 今日已结算订单收益总和（今日创建或今日更新且状态为9的订单）
        from django.db.models import Q
        today_settled_profit = models.OrderListV2.objects.filter(
            Q(create_time__gte=today_start) | Q(update_time__gte=today_start), 
            status=9
        ).aggregate(total_profit=Sum('completed_profit'))['total_profit'] or 0
        
        # 平均接单价格
        avg_receiving_price = models.OrderListV2.objects.aggregate(avg_price=Sum('receiving_price'))['avg_price'] or 0
        avg_receiving_price = avg_receiving_price / total_orders if total_orders > 0 else 0
        
        # 平均发单价格
        avg_posting_price = models.OrderListV2.objects.aggregate(avg_price=Sum('posting_price'))['avg_price'] or 0
        avg_posting_price = avg_posting_price / total_orders if total_orders > 0 else 0
        
        # 平均利润
        avg_profit = (total_completed_profit / total_orders) if total_orders > 0 else 0
        
        # 最近7天的订单趋势
        last_7_days = []
        for i in range(7):
            date = today - timedelta(days=i)
            date_str = date.strftime('%Y-%m-%d')
            date_start = datetime.combine(date, datetime.min.time())
            date_end = datetime.combine(date, datetime.max.time())
            
            day_orders = models.OrderListV2.objects.filter(create_time__range=(date_start, date_end)).count()
            day_profit = models.OrderListV2.objects.filter(create_time__range=(date_start, date_end)).aggregate(day_profit=Sum('completed_profit'))['day_profit'] or 0
            
            last_7_days.append({
                'date': date_str,
                'orders_count': day_orders,
                'profit': float(day_profit)
            })
        
        # 按区服统计订单数量
        server_counts = models.OrderListV2.objects.values('receiving_server').annotate(count=Count('receiving_server')).order_by('-count')[:10]
        server_data = [{item['receiving_server'] or '未设置': item['count']} for item in server_counts]
        
        # 准备响应数据
        response_data = {
            # 基础指标
            'total_orders': total_orders,                  # 总发单量
            'today_orders': today_orders,                  # 今日发单量
            
            # 状态分布
            'status_distribution': list(status_data.values()),  # 各状态订单数量
            
            # 收益相关
            'total_completed_profit': float(total_completed_profit),  # 全部订单完成收益总和
            'today_completed_profit': float(today_completed_profit),  # 今日订单完成收益总和
            'settled_orders_profit': float(settled_orders_profit),  # 已完结订单收益总和（状态为9的订单）
            'today_settled_profit': float(today_settled_profit),  # 今日已结算订单收益总和（今日创建且状态为9的订单）
            
            # 计算指标
            'completion_rate': round(completion_rate, 2),  # 订单完成率（%）
            'avg_receiving_price': float(avg_receiving_price),  # 平均接单价格
            'avg_posting_price': float(avg_posting_price),      # 平均发单价格
            'avg_profit': float(avg_profit),                    # 平均利润
            
            # 趋势数据
            'last_7_days_trend': list(reversed(last_7_days)),  # 最近7天趋势
            
            # 分布数据
            'top_10_servers': server_data  # 前10个区服的订单数量
        }
        
        return order_v2_utils.response_dict(data=response_data, message="获取订单数据分析报告成功")
        
    except Exception as e:
        return order_v2_utils.response_dict(message=f"获取分析报告失败: {str(e)}", code=1)


def get_order_status_summary(request):
    """获取订单状态简要统计
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含订单状态简要统计的JSON响应
    """
    if request.method != 'GET':
        return order_v2_utils.response_dict(message="请使用GET请求", code=1)
    
    try:
        # 各status状态的订单数量
        status_counts = models.OrderListV2.objects.values('status').annotate(count=Count('status')).order_by('status')
        status_data = {}
        status_text_map = dict(models.OrderListV2.STATUS_CHOICES)
        
        for item in status_counts:
            status_code = item['status']
            status_data[status_code] = {
                'code': status_code,
                'name': status_text_map[status_code],
                'count': item['count']
            }
        
        # 确保所有状态都有数据
        for code, name in models.OrderListV2.STATUS_CHOICES:
            if code not in status_data:
                status_data[code] = {
                    'code': code,
                    'name': name,
                    'count': 0
                }
        
        response_data = list(status_data.values())
        return order_v2_utils.response_dict(data=response_data, message="获取订单状态统计成功")
        
    except Exception as e:
        return order_v2_utils.response_dict(message=f"获取订单状态统计失败: {str(e)}", code=1)


def get_order_profit_analytics(request):
    """获取订单利润分析
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含订单利润分析的JSON响应
    """
    if request.method != 'GET':
        return order_v2_utils.response_dict(message="请使用GET请求", code=1)
    
    try:
        # 获取今天的日期
        today = datetime.now().date()
        today_start = datetime.combine(today, datetime.min.time())
        
        # 全部订单完成收益总和
        total_completed_profit = models.OrderListV2.objects.aggregate(total_profit=Sum('completed_profit'))['total_profit'] or 0
        
        # 今日订单完成收益总和
        today_completed_profit = models.OrderListV2.objects.filter(create_time__gte=today_start).aggregate(total_profit=Sum('completed_profit'))['total_profit'] or 0
        
        # 未完成订单收益总和
        total_uncompleted_profit = models.OrderListV2.objects.aggregate(total_profit=Sum('uncompleted_profit'))['total_profit'] or 0
        
        # 按状态分组的利润统计
        status_profit = models.OrderListV2.objects.values('status').annotate(
            total_completed_profit=Sum('completed_profit'),
            total_uncompleted_profit=Sum('uncompleted_profit'),
            count=Count('status')
        ).order_by('status')
        
        status_text_map = dict(models.OrderListV2.STATUS_CHOICES)
        profit_by_status = []
        
        for item in status_profit:
            status_code = item['status']
            profit_by_status.append({
                'status_code': status_code,
                'status_name': status_text_map[status_code],
                'completed_profit': float(item['total_completed_profit'] or 0),
                'uncompleted_profit': float(item['total_uncompleted_profit'] or 0),
                'order_count': item['count']
            })
        
        # 准备响应数据
        response_data = {
            'total_completed_profit': float(total_completed_profit),
            'today_completed_profit': float(today_completed_profit),
            'total_uncompleted_profit': float(total_uncompleted_profit),
            'profit_by_status': profit_by_status
        }
        
        return order_v2_utils.response_dict(data=response_data, message="获取订单利润分析成功")
        
    except Exception as e:
        return order_v2_utils.response_dict(message=f"获取订单利润分析失败: {str(e)}", code=1)